package com.turtle.learning.contents.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.turtle.learning.contents.dto.AuditDTO;
import com.turtle.learning.contents.entity.RocketmqTransactionLog;
import com.turtle.learning.contents.entity.Share;
import com.turtle.learning.contents.enums.AuditStatusEnums;
import com.turtle.learning.contents.mapper.RocketmqTransactionLogMapper;
import com.turtle.learning.contents.mapper.ShareMapper;
import com.turtle.learning.contents.service.IShareService;
import com.turtle.learning.users.dto.UserAddBonusMsgDTO;
import lombok.RequiredArgsConstructor;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

/**
 * 分享表 服务实现类
 *
 * @author turtle
 * @since 2020-04-26
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ShareServiceImpl extends ServiceImpl<ShareMapper, Share> implements IShareService {

    private final ShareMapper shareMapper;
    private final RocketMQTemplate rocketMQTemplate;
    private final RocketmqTransactionLogMapper rocketmqTransactionLogMapper;


    /**
     * 审核文章
     *
     * @param id       文章id
     * @param auditDTO 审核实体
     * @return Share
     */
    @Override
    public Share auditById(Integer id, AuditDTO auditDTO) {
        // 判断文章是否存在或已被审核
        Share share = shareMapper.selectById(id);
        if (share == null) {
            throw new IllegalArgumentException("参数非法，该文章不存在");
        }
        if (!share.getAuditStatus().equals(AuditStatusEnums.NOT_YET.toString())) {
            throw new IllegalArgumentException("参数非法，该文章已审核通过或拒绝");

        }

        if (auditDTO.getAuditStatusEnum().equals(AuditStatusEnums.PASS)) {

            // 发送半消息
            String transactionId = UUID.randomUUID().toString();
            rocketMQTemplate.sendMessageInTransaction(
                "add-bonus-group",
                "audit-topic",
                MessageBuilder
                    .withPayload(
                        UserAddBonusMsgDTO.builder()
                            .userId(share.getUserId())
                            .bonus(50)
                            .build()
                    )
                    .setHeader(RocketMQHeaders.TRANSACTION_ID, transactionId)
                    .setHeader("share_id", id)
                    .build(),
                auditDTO
            );

//            rocketMQTemplate.convertAndSend("audit-topic", UserAddBonusMsgDTO.builder()
//                .userId(share.getUserId())
//                .bonus(50)
//                .build()
//            );
        } else {
            this.auditByIdInDb(id, auditDTO);
        }

        return share;
    }

    /**
     * 修改文章状态
     *
     * @param id       文章id
     * @param auditDTO 审核实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void auditByIdInDb(Integer id, AuditDTO auditDTO) {
        Share share = Share.builder()
            .id(id)
            .auditStatus(auditDTO.getAuditStatusEnum().toString())
            .reason(auditDTO.getReason())
            .build();
        shareMapper.updateById(share);

    }

    /**
     * 审核消息日志
     *
     * @param id            文章id
     * @param auditDTO      审核实体
     * @param transactionId 事务id
     */
    @Transactional(rollbackFor = Exception.class)
    public void auditByIdWithRocketMqLog(Integer id, AuditDTO auditDTO, String transactionId) {
        this.auditByIdInDb(id, auditDTO);
        RocketmqTransactionLog rocketmqTransactionLog = RocketmqTransactionLog.builder()
            .transactionId(transactionId)
            .log("文章审核")
            .build();
        rocketmqTransactionLogMapper.insert(rocketmqTransactionLog);
    }
}
